<template>
	<div class="page flexDirection">
		<div class="search flex" style="background-color: #3975f6; padding-right: 20rpx">
			<div style="
          justify-content: center;
          margin: 0 -10rpx 0 20rpx;
          font-size: 28rpx;
        " class="flexCenter" @click="showFilterPop = true">
				<div style="margin-right: 6rpx; color: #fff">
					{{ filterList[currentFilterIndex]?.name }}
				</div>
				<van-icon name="arrow-down" color="#fff" />
			</div>
			<van-search :value="searchText" shape="round" background="#3975F6" placeholder="请输入关键字搜索（包含）"
				style="flex: 1" @search="getList" @change="changeSearchText" />
			<!-- <van-icon name="scan" color="#fff" size="20" /> -->
		</div>
		<div style="flex: 1; overflow: hidden">
			<scroll-view scroll-y type="list" style="height: 100%" @scrolltolower="scrollTolower">
				<div class="purse" :style="{ 'padding-bottom': 200 + utils.windowBottom + 'rpx' }">
					<div class="p_item" v-for="(item, index) in orderList" :key="index" @click.stop="toDetail(item)">
						<!-- <div class="title">
              <span>{{ item.FBillNo.value }}</span>
              <span class="status">{{
                utils.getOrderStatus(item.FDocumentStatus?.value)
              }}</span>
            </div> -->
						<div class="content flex">
							<template v-for="(v, key) in item" :key="key">
								<div class="c_item" :style="{ width: v.name == '创建日期' ? '100%' : '50%' }"
									v-if="v && v?.name != '状态'">
									<div style="
                      color: #999;
                      margin-bottom: 4rpx;
                      align-items: center;
                    " class="flex">
										{{ v?.name }}
										<span v-if="v.name == '单据编号'" style="color: #dd3f5b; font-size: 24rpx">{{
                        '（' +
                        utils.getOrderStatus(item?.FDocumentStatus?.value) +
                        '）'
                      }}</span>
									</div>

									<div>
										{{
                      v?.name.includes('日期')
                        ? formatDate(new Date(v.value))
                        : v?.value
                    }}
									</div>
								</div>
							</template>
						</div>


					</div>
				</div>
			</scroll-view>
		</div>

		<van-action-sheet :show="showFilterPop" :actions="filterList" @close="showFilterPop = false"
			@select="selectFilter" />
		<template v-if="Utils.getLoginType() != '客户'">
			<ButtonBottom :button-data="{ name: '新增' }" @click-btn="add"></ButtonBottom>
		</template>

	</div>
</template>

<script setup lang="ts">
	import ButtonBottom from '@/components/buttonBottom.vue';
	import { getOrderList } from '@/api/user';
	import utils from '@/utils';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { computed, ref } from 'vue';
	import { useStore } from 'vuex';
	import { Utils } from '@/utils/utils';
	const { commit, getters } = useStore();


	/**
	 * 过滤条件列表
	 */
	const filterList = ref([
		{ name: '编号', value: 0, key: 'FBillNo' }
	]);
	const currentFilterIndex = ref(0);
	const showFilterPop = ref(false);
	const selectFilter = (e : any) => {
		currentFilterIndex.value = e.detail.value;
	};
	// 数据筛选
	const dataScreening = {
		入库单: {
			FBillNo: { name: '单据编号', value: '' },
			FDocumentStatus: { name: '状态', value: '' },
			'FOwnerIdHead.FName': { name: '货主', value: '' },
			// 'FBillTypeID.FNUMBER' : { name: '单据类型', value: '' },
			FDate: { name: '日期', value: '' },


		},
		调拨单: {
			FBillNo: { name: '单据编号', value: '' },
			FDocumentStatus: { name: '状态', value: '' },
			'FStockOrgId.FName': { name: '调入库存组织', value: '' },
			'FOwnerIdHead.FName': { name: '调入货主', value: '' },
			// "FOwnerOutIdHead.FName": { name: '货主类型', value: '' }
			
		},
		出库单: {
			FBillNo: { name: '单据编号', value: '' },
			FDocumentStatus: { name: '状态', value: '' },
			'FCustId.FName': { name: '客户', value: '' },
			FDate: { name: '日期', value: '' },
		},
		
	} as any;
	// 当前页面数据
	const currentPageScreening = ref({} as any);
	// 搜索关键词
	const searchText = ref('');
	/**
	 * 获取列表数据
	 */
	const orderList = ref();
	// 请求参数
	const requestParams = ref({
		FormId: '',
		FieldKeys: '',
		FilterString: [],
		OrderString: '',
		TopRowCount: 0,
		StartRow: 0,
		Limit: 2000,
	} as any);
	const getList = async () => {

		const params = JSON.parse(JSON.stringify(requestParams.value));
		const FilterString = [];
		// orderList.value = [];
		FilterString.push(
			Utils.getFilterString(filterList.value[currentFilterIndex.value].key, searchText.value, 'Like', '', '')
		);
		params.FormId = Utils.getFormId(pageParams.value);
		const OrderString = pageParams.value == '入库单' ? 'FCreateDate' : 'FCreateDate';
		if (Utils.getLoginType() == '客户') {
			FilterString.push(
				Utils.getFilterString(
					'F_Customer.FNumber',
					Utils.getStorage('currentCustomer')?.FNumber || 'null',
					'67',
					'(',
					''
				)
			)
			FilterString.push(
				Utils.getFilterString(
					'FDocumentStatus',
					'C',
					'=',
					'',
					')'
				)
			)
		}
		// 查询字段
		params.FieldKeys =
			objKey(currentPageScreening.value).join(',') + ',' + OrderString;
		// 排序字段
		params.OrderString = OrderString + ' desc';
		params.FilterString = FilterString;

		const res : any = await getOrderList({
			data: JSON.stringify(params),
		});
		if (res.length == 0) {
			orderList.value = [];
			return utils.showToast('暂无数据');
		}
		// 获取数据失败
		if (res[0][0]?.Result?.ResponseStatus.IsSuccess === false) {
			orderList.value = [];
			return utils.showErr(res[0][0]?.Result?.ResponseStatus?.Errors[0]?.Message);
		}

		orderList.value = res.map((item : any, index : number) => {
			let obj = JSON.parse(JSON.stringify(currentPageScreening.value));
			item.forEach((v : string, i : number) => {
				// 获取对象的所有属性名组成的数组
				const keys = Object.keys(currentPageScreening.value);
				// 通过索引获取属性名
				const key = keys[i];
				if (key) {
					// 使用属性名访问对象的属性
					obj[key].value = v;
				}
			});

			return obj;
		});
	};

	// 搜索关键词
	const changeSearchText = (e : any) => {
		searchText.value = e.detail;
	};
	/**
	 * 拼接对象的key方法
	 * @param obj
	 * @returns
	 */
	const objKey = (obj : any) => {
		return Object.keys(obj);
	};
	/**
	 * 滚动到底部
	 */
	const isMoreData = ref(true);
	const scrollTolower = (e : any) => {
		if (isMoreData.value) {
			// pageNum.value++;
			// queryZyTalentLibraryListFn();
		}
	};

	const toDetail = (item ?: any) => {
		const serviceType = Utils.getLoginType() == '客户' ? { pageUrl: 'dzd' } : Utils.getOneServiceType(pageParams.value)
		if (Utils.getLoginType() == '客户') {
			wx.requestSubscribeMessage({
				tmplIds: ['rAG8ViGLQH99zGxJASwSpTC4zd7OQg0_kk4zNacOUeI'],
				success(res) {
					utils.navigateTo(
						'order/' +
						serviceType?.pageUrl +
						'/index?title=' +
						pageParams.value +
						'&FBillNo=' +
						item?.FBillNo?.value
					);
				}
			})
		} else {
			utils.navigateTo(
				'order/' +
				serviceType?.pageUrl +
				'/index?title=' +
				pageParams.value +
				'&FBillNo=' +
				item?.FBillNo?.value
			);
		}



	};
	const formatDate = (date : any) => {
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		return `${year}-${month}-${day}`;
	};

	/**
	 * 新增
	 */
	const add = () => {
		// 允许从相机扫码
		// uni.scanCode({
		// 	onlyFromCamera: true,
		// 	success(res) {
		// 		console.log(res);
		// 		if (!res || res.errMsg != 'scanCode:ok')
		// 			return Utils.showErr('获取仪表信息失败！');
		// 		// 仪表编码
		// 		const code = res.result;
		// 		// 获取仪表信息
		// 		const serviceType = Utils.getOneServiceType(pageParams.value);
		// 		utils.navigateTo(
		// 			'order/' +
		// 			serviceType?.pageUrl +
		// 			'/index?title=' +
		// 			pageParams.value +
		// 			'&code=' +
		// 			code
		// 		);
		// 	},
		// });

		const serviceType = Utils.getOneServiceType(pageParams.value);
		utils.navigateTo(
			'order/' + serviceType?.pageUrl + '/index?title=' + pageParams.value
		);
	};
	onShow(() => {
		getList();
	});
	// 页面参数
	const pageParams = ref();
	onLoad((opt) => {
		if (opt && opt.title) {
			pageParams.value = opt.title;
			if (opt.title == '对账单') {
				filterList.value = [
					{ name: '合同号', value: 0, key: 'F_ContractCode' }
				]
			}

			// 设置页面标题
			utils.setPageTitle(opt.title || '订单');
			// 设置当前页面数据keys
			for (const key in dataScreening) {
				if (Object.prototype.hasOwnProperty.call(dataScreening, key)) {
					if (pageParams.value == key) {
						currentPageScreening.value = dataScreening[key];
					}
				}
			}
		}
	});
</script>

<style lang="less" scoped>
	.purse {
		padding: 16rpx 25rpx 160rpx;
		width: 100%;
		background: #f6f6f6;

		.p_item {
			padding: 20rpx 22rpx;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			background: #fff;
			font-size: 30rpx;

			.title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 2rpx 0 24rpx;
				border-bottom: 1px solid #eeeeee;
				font-weight: 500;
				font-size: 34rpx;
				color: #000000;

				.status {
					color: #3974f6;
					font-size: 22rpx;
				}
			}

			.content {
				flex-wrap: wrap;
				padding-top: 20rpx;

				.c_item {
					width: 50%;
					margin-bottom: 26rpx;
					color: #111;
				}
			}

			.btn {
				display: flex;
				justify-content: flex-end;
				padding-top: 12rpx;

				view {
					padding: 12rpx 24rpx;
					border-radius: 10rpx;
					background: #3974f6;
					color: #fff;
				}
			}
		}
	}
</style>